package com.yunc.modules.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.controller.CommonController;
import com.yunc.common.utils.R;
import com.yunc.modules.sys.entity.SysNotice;
import com.yunc.modules.sys.service.ISysNoticeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 通知公告
 *
 * @author congcong tao
 * @create 2018/12/16 6:34 PM
 */
@RestController
@RequestMapping("sysNotice")
public class SysNoticeController extends CommonController {

    private static final Logger logger = LogManager.getLogger(SysNoticeController.class);

    @Autowired
    private ISysNoticeService sysNoticeService;

    @GetMapping("/page")
    public R page(Page<SysNotice> page, SysNotice sysNotice){
        List<SysNotice> sysNoticeList = sysNoticeService.pageInfo(page, sysNotice);
        return R.ok().put("data", sysNoticeList).put("count", page.getTotal());
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable String id){
        SysNotice notice = sysNoticeService.getById(id);
        return R.ok().put("sysNotice", notice);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("sys:notice:save")
    public R save(@RequestBody SysNotice notice){
        notice.setCreateTime(new Date());
        boolean flag = sysNoticeService.save(notice);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @PutMapping(value = "/update")
    @RequiresPermissions("sys:notice:update")
    public R update(@RequestBody SysNotice notice){
        boolean flag = sysNoticeService.updateById(notice);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{ids}")
    @RequiresPermissions("sys:notice:delete")
    public R delete(@PathVariable String ids){
        if (StringUtils.isEmpty(ids)) {
            return R.error("传入值为空");
        }
        List<String> idsList = StrSpliter.split(ids, ',', 0, true, true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = sysNoticeService.removeByIds(idsList);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}
